package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author 孤风雪影
 * @date 2021/1/5
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    /**
     * / 与 /index.html默认返回首页
     * @param model
     * @return
     */
    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        // 1.查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories", categoryEntities);
        return "index";
    }

    //index/catalog.json,由JS动态发出的请求
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        Map<String, List<Catalog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    /**
     * hello请求，测试分布式锁
     * @param model
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(Model model) {
        //1.获取一把锁,只要锁名字一样,就是一把锁
        RLock lock = redissonClient.getLock("my-lock");

        //2.加锁
        lock.lock(); //阻塞式等待
        //看门狗,自己的锁,自动续期默认30秒
        //业务只要完成,就不会续期
        try {
            System.out.println("加锁成功,执行业务..."+Thread.currentThread().getId());
            Thread.sleep(10000);
        } catch (Exception e) {

        } finally {
            //3.解锁
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }

    /**
     * 预留接口，发现页，discover
     * @return
     */
    @ResponseBody
    @GetMapping("/discover")
    public String discover() {
        return "discover";
    }
}
